package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author solang
 * @date 2022-12-26 16:09
 */
@RestController
@Slf4j
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增分类
     *
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category) {
        log.info("category:{}", category);
        categoryService.save(category);
        return R.success("新增分类成功");
    }
    @PutMapping
    public R<String> update(@RequestBody Category category){
//        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.eq(category.getId()!=null,Category::getId,category.getId());
        categoryService.updateById(category);
        log.info("进入修改流程");
        return R.success("修改成功");
    }
    /**
     * 分类分页
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize) {
        //分页构造器
        Page<Category> pageInfo = new Page(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加排序条件,根据sort进行排序
        queryWrapper.orderByAsc(Category::getSort);
        //进行分页查询
        categoryService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 根据ids删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long ids) {
//        categoryService.removeById(ids);
        categoryService.remove(ids);
        return R.success("删除成功");

    }

    /**
     * 查询分类
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> List2(Category category){
        //构造条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件,当传入的值不为空时执行,条件为Category属性Type,传入的Type
        queryWrapper.eq(category.getType()!=null,Category::getType,category.getType());
        //增加排序,升序根据Category的Sort,当排序等级一致时,根据Category的CreateTime创建时间降序
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getCreateTime);
        //使用mybatis-plus的list进行查询
        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }
}
